/**
 * 
 */
var customerinformation = {
	name: "Samuel Lu",
	credit: 1000000,
	location: "(wish) Washington D.C., United States",
	orderType: 1
};
window.driverOrderNo = 0;
window.numOrders = 0;
$("#histOrderBtn").on("click",function(){
	$.mobile.changePage("../view/driver-book-history.html");
});
$("#desperateBtn").on("click", function(){
	$.mobile.changePage("../view/driver-book-find.html");
});
$("#roadcdtBtn").on("click",function(){
	$.mobile.changePage("../view/road-condition.html");
});

//enable and disable the voice
/*$('#availableCheckbox').on('click',function(){
	//alert($('#availableCheckbox').is(":checked"));
	$('#silentCheckbox').attr('checked', false).checkboxradio('refresh');
//	$('#availableCheckbox').attr('checked', true);
	
//	$('#availableCheckbox.lable').attr('disabled', true);
//	$('#silentCheckbox').removeAttr('disabled');
});

$('#silentCheckbox').on('click',function(){
	//alert($('#silentCheckbox').is(":checked"));
	if ($('#availableCheckbox').is(":checked")){
		$('#availableCheckbox').attr('checked', false).checkboxradio('refresh');
	}
	
//	$('#availableCheckbox').attr('checked', false);
//	$('#silentCheckbox').attr('check', false);
//	$('.driverCheckbox').removeClass('disabled');
	//$('#availableCheckbox').removeAttr('disabled');
//	$('#availableCheckbox').attr('disabled', '');
//	$('input#silentCheckbox').attr('disabled', true);
//	$(input[name='checkbox1']).removeAttr('disabled');
});*/


$('#availableCheckbox').bind('change',function(event, data){
	if($('input:radio[name=driverCheckbox]:checked').val()=='availableCheckbox'){
		$('#microphoto').show();
	}	
});
$('#silentCheckbox').bind('change',function(event, data){
	if($('input:radio[name=driverCheckbox]:checked').val() == 'silentCheckbox'){
		$('#microphoto').hide();
		$('#voicecontainerD').hide();
	}
});

//addCustomerInfo(customerinformation);
/**
 * 
 * @param customerInfo
 * 		name: (string)
 * 		credit: (int)
 * 		location: (string)
 * 		orderType: (int)
 */
function addCustomerInfo(customerInfo){
	$("#noOrderText").addClass("hidden");
	var custInfoId = "custInfo" + window.driverOrderNo;
	var orderType = "now";
	if(customerInfo.orderType == 1){
		orderType = "order";
	}
	$("#driverCurOrders").prepend("<div id = '" + custInfoId + "'class='boxed'></div><br>");
			
	$("#" + custInfoId).append("<p>Name: " + customerInfo.name+"</p><p> " +
			"Credit: " + customerInfo.credit + "</p><p> Location: " + customerInfo.location 
			+"</p><p>Order Type: "+ orderType + "</p>");
	
	$("#" + custInfoId).append("<a data-role='button' id='acceptCustBtn"
			+window.driverOrderNo+"' data-inline='true' class='mainBtn'>Accept</a>");
	
	$("#" + custInfoId).append("<a data-role='button' id='refuseCustBtn"
			+window.driverOrderNo+"' data-inline='true' class='mainBtn'>Refuse</a>");
	
	$("#refuseCustBtn" + window.driverOrderNo).on("click", function(){
		$(this).parent().remove();
		window.numOrders--;
		if(window.numOrders == 0){
			$("#noOrderText").removeClass("hidden");
		}
	});
	window.numOrders ++;
	window.driverOrderNo ++;
}

/**
 * popup order info
 */

//setTimeout(function() {
//	var d = {name: "Jane Zheng", credit: 4};
//	var o = {time: "08/21/2013 11:00", fromAddr: "中国上海市上海浦东新区张江", toAddr: "上海火车站"};
//	receiveOrderAccept(d, o);
//}, 2000);
function showNotification(){
	alert("showNotification");
	var strs=window.pushOrder.split(",");
	var i=0;
	var c = {id:(strs[i++].split(":"))[1],name: (strs[i++].split(":"))[1], credit: (strs[i++].split(":"))[1]};
	var o = {id:(strs[i++].split(":"))[1],time: (strs[i++].split(":"))[1]+":"+(strs[i-1].split(":"))[2], fromAddr:(strs[i++].split(":"))[1] , toAddr: (strs[i++].split(":"))[1]};
	//alert("111");
	receiveOrderAccept(c, o);
	//test22();
	//alert("222");
};
function test221(){
	alert("test");
}
function receiveOrderAccept(cus_info, order_info) {
	
	alert("receiveOrderAccept");
	$("#namePopup").text(cus_info.name);
	var credit = cus_info.credit;
	alert("credit"+credit);
	for(var i = 0; i < credit; i++) {
		$("<img src='../images/star.png' width='14px' height='14px' />").appendTo($("#creditPopup"));
	}
	$("#timePopup").text(order_info.time);
	$("#fromAddrPopup").text(order_info.fromAddr);
	$("#toAddrPopup").text(order_info.toAddr);
	$("#driorderPopup").popup("open");
	window.id=0;
	$("#testBtn").on('click',function(){
		alert("test");
	});
	$("#driAcceptBtn").on('click', function() {
		alert("request has been sent!"+window.id);
		window.id++;
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'driAcceptOrder',
	 		    parameters : [{'dri_id':window.driver.id, 'order_id': order_info.id,'cus_id':cus_info.id }]
				
			};	
		WL.Client.invokeProcedure(invocationData,{
			onSuccess : driAcceptSuccess,
			onFailure : driAcceptFailure
		});	
		$("#driorderPopup").popup("close");
		$("#creditPopup img").remove();
		
	});
	
	setTimeout(function(){
		$("#driorderPopup").popup("close");
		$("#creditPopup img").remove();
	},10000);
}

function driAcceptSuccess(result) {
	
	if(result.invocationResult.status == 0){
		alert("driAcceptSuccess");
//		if (WL.Client.Push){
//			WL.Client.Push.onReadyToSubscribe = function(){
//				alert("onReadyToSubscribe");
//
//				WL.Client.Push.registerEventSourceCallback(
//						"acceptPush", 
//						"stAdp", 
//						"PushEventSource", 
//						test);
//				};
//			
//			}
//		doSubscribe();
	}else if(result.invocationResult.status == 1){
		alert("order has been accepted by other driver");	
	}else{		
		alert("system error");	
	}
}
function doSubscribe(){
	alert("doSubscribeaccept");
	WL.Client.Push.subscribe("acceptPush", {
		onSuccess: doSubscribeSuccess,
		onFailure: doSubscribeFailure
	});
}

function doSubscribeSuccess(){
	alert("doSubscribeSuccess");
}

function doSubscribeFailure(){
	alert("doSubscribeFailure");
}
function test(props, payload){
	alert("pushNotificationReceived invoked");
	//alert("props :: " + JSON.stringify(props.alert));
	//window.pushOrder=props.alert;
	alert("props :: " + JSON.stringify(props));
	//alert("yes");
	//showNotification();
	alert("payload :: " + JSON.stringify(payload));
}
function driAcceptFailure(result) {
	//alert(result);
	//busy.hide();
	alert("driAcceptFailure");
	myBusyIndicator.hide();
	alert("login request failure");	
	WL.Logger.error("login request failure");
	
}

//------------------------------------- record -----------------------------
var recordMedia = null;
//html element
var loadingRecord = null;
var recordSrc = "record.ogg";
var playSrc = "play.ogg";
$("#microphoto").on('tap',function(){
	initVoicePanel();
	$("#voicecontainerD").slideToggle("slow");
});

/**
 * initialize the voice container panel, take out lastest 6 records which have the biggest record time
 */
function initVoicePanel() {
	var status = $("#voicecontainerD").css('display');
	if(status != "none") {
//		alert("none");
		return;
	}
//	alert(document.getElementById('recordHistory').childElementCount);
	if(document.getElementById('recordHistory').childElementCount != 0) {
//		alert("has child");
		return;
	}
	var findAllSuccess = function(data) {
		$.each(data, function(i, obj) {
			var record = obj.json;
			var objid = obj._id;
//			alert(record.cus_id + " " + record.dri_id);
//			alert(window.customer.id +  " " + window.backResult.driverInfo.id);
			var dateTime = new Date();
			dateTime.setTime(record.recordTime);
			var timeString = dateTime.getFullYear() + "/" + dateTime.getMonth() + "/" + dateTime.getDate() + " " + dateTime.getHours() + ":" + dateTime.getMinutes() + ":" + dateTime.getSeconds();
//			alert(timeString);
			
			if(record.dri_id == 0 && record.cus_id == window.customer.id) {
				//the current user is costomer
				var right = $("<div class='right'><span class='triangle-border right'>" + timeString + "</span><img src='../images/defaultPhoto.png' width='40px' height='40px'></div>");
				right.on('tap', function() {playRecordById(objid);});
				right.appendTo($("#recordHistory"));
			}else if(record.dri_id == window.backResult.driverInfo.id && record.cus_id == window.customer.id) {
				//the current record is record by current booking driver
				var left = $("<div class='left'><span class='triangle-border left'>" + timeString + "</span><img src='../images/defaultPhoto.png' width='40px' height='40px'></div>");
				left.on('tap', function() {playRecordById(objid);});
				left.appendTo($("#recordHistory"));
			}
		});
	};	
	var findAllFailure = function(err) {
		alert("findAllFailure");
		alert(JSON.stringify(err));
	};
	var options = {onSuccess: findAllSuccess, onFailure: findAllFailure}; 
	window.audioJS.count()
	.then(function(numberOfDocuments) {
		if(numberOfDocuments == 0)return;
		if(numberOfDocuments > 4) {
			window.currentOffset = options.offset = numberOfDocuments - 4;
			options.limit = 4;
//			alert("currentOffset::" + window.currentOffset);
		}
		window.audioJS.findAll(options);
	})
	.fail(function() {
		alert("count failure");
		window.audioJS.findAll(options);
	});
	
}

/**
 * get the encodedString from JSONStore according to the id and decode the audio and play it 
 */
function playRecordById(objid) {
	alert("playRecord" + objid);
	//get the encodedString from JSONStore according to the id
	var query = {_id : objid};
	window.audioJS.find(query, {})
	.then(function(data) {
		alert(JSON.stringify(data));
		var encodedContent = data[0].json.encodedString;
		alert(encodedContent);
		playRecordByContent(encodedContent);
	})
	.fail(function(err) {
		alert("find fail");
		alert(JSON.stringify(err));
	});

}
/**
 * when decode success play it
 * @param result
 */
function decodeSuccess(result) {
	alert("decodeSuccess");
	var mediaPlayer = new Media(playSrc, function() {
		alert("playAudio():Audio new Success");
	}, function(err) {
//		alert("playAudio():Audio new Error: " + err);
	}, function(status) {
//		alert("playAudio():Audio Status: " + Media.MEDIA_MSG[status]);
	});
	mediaPlayer.play();
}

/**
 * when decode fail , remind user decode fail
 * @param result
 */
function decodeFailure(result) {
	alert("decodeFail:");
}

/**
 * add listener of voice btn
 */
$("#voiceBtn").on("tap", function(){
//	alert("tap btn");
	var currentStatus = $('#voiceBtn').data('status');
	if (currentStatus == "stop") {
//		alert("currentStatus=stop");
		$('#voiceBtn .ui-btn-text').text("stop");
		$('#voiceBtn').data('status', "running");
		startRecordAudio();
	} else if (currentStatus == "running") {
//		alert("currentStatus=running");
		$('#voiceBtn .ui-btn-text').text("record");
		$('#voiceBtn').data('status', "stop");
		stopRecordAudio();
	}
});

/**
 * add listener of more btn
 * load 6 more record once
 */
$("#moreBtn").on('tap', function() {
	var findAllSuccess = function(data) {
		alert("findAllSuccess");
		var size = data.length;
//		alert("size::" + size);
		for(var i = 1; i <= size; i++) {
//			alert("i::" + i);
			var record = data[size - i].json;
//			alert("record::" + JSON.stringify(record));
			var objid = data[size - i]._id;
//			alert(record.cus_id + " " + record.dri_id);
//			alert(window.customer.id +  " " + window.backResult.driverInfo.id);
			alert("objid:::" + objid);
			if(record.dri_id == 0 && record.cus_id == window.customer.id) {
				//the current user is costomer
				var right = $("<div class='right'><span class='triangle-border right'>ccccc</span><img src='../images/defaultPhoto.png' width='35px' height='40px'></div>");
				right.on('tap', function() {playRecordById(objid);});
				right.prependTo($("#recordHistory"));
			}else if(record.dri_id == window.backResult.driverInfo.id && record.cus_id == window.customer.id) {
				//the current record is record by current booking driver
				var left = $("<div class='left'><span class='triangle-border left'>ccccc</span><img src='../images/defaultPhoto.png' width='35px' height='40px'></div>");
				left.on('tap', function() {playRecordById(objid);});
				left.prependTo($("#recordHistory"));
			}
		}
	};	
	var findAllFailure = function(err) {
		alert("findAllFailure");
		alert(JSON.stringify(err));
	};
	var options = {onSuccess: findAllSuccess, onFailure: findAllFailure}; 
	window.audioJS.count()
	.then(function(numberOfDocuments) {
		if(numberOfDocuments == 0 || window.currentOffset == 0){alert("no more record");return;};
		if(window.currentOffset - 4 >= 0) {
			window.currentOffset = options.offset = window.currentOffset - 4;
			options.limit = 4;
			alert("currentOffset::" + window.currentOffset);
		} else if(window.currentOffset < 4) {
			options.limit = window.currentOffset;
			window.currentOffset = options.offset = 0;
			alert("currentOffset::" + window.currentOffset);
		}
		window.audioJS.findAll(options);
	})
	.fail(function() {
		alert("count failure");
		window.audioJS.findAll(options);
	});
});
/**
 * initialize a media to record audio
 */
function startRecordAudio() {
	alert("startRecord");
	if (recordMedia == null) {
		var recAudioSuccess = function() {
			alert("startRecordAudio():Audio new Success");
		};
		var recAudioError = function(err) {
//			alert("startRecordAudio():Audio Error: " + err);
		};
		var recAudioStatus = function(status) {
//			alert("startRecordAudio():Audio Status: " + Media.MEDIA_MSG[status]);
		};
		recordMedia = new Media(recordSrc, recAudioSuccess, recAudioError,
				recAudioStatus);
	}
	recordMedia.startRecord();
}

/**
 * stop record then encode the record and send out
 */
function stopRecordAudio() {
//	alert("stop record audio");
	recordMedia.stopRecord();
	addLoadingRecord();
	cordova.exec(encodeSuccess, encodeFailure, "EncodeUtilPlugin", "encodeAudio", [recordSrc]);
}

/**
 * append a voice record on voice container
 */
function addLoadingRecord() {
	loadingRecord = $("<div class='right'><span class='triangle-border right sending'>ccccc</span><img src='../images/defaultPhoto.png' width='35px' height='40px'></div>");
	loadingRecord.appendTo($("#recordHistory"));
//	alert(document.getElementById('recordHistory').childElementCount);
}

/**
 * encode success ,save it to json store and send it to server
 * the key of the record in json store is userid_currenttime
 */
function encodeSuccess(result) {
//	alert("encodedSuccess;" + result);
	window.tmp = result;
	var encodedContent = result;
	var cus_id = window.customer.id;
	var dri_id = window.backResult.driverInfo.id;
	//save to the json store
	var time = (new Date()).getTime();
	var data = {cus_id: window.customer.id, dri_id: '0', recordTime: time, encodedString : result};
	window.audioJS.add(data, {})
	.then(function () {
//		alert("insert audio success");
		loadingRecord.on('tap', function(ec) {
			return function() {alert("ppp");playRecordByContent(ec);};
		}(encodedContent));
		//send to the server
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'sendAudio',
				parameters : [{'cus_id': cus_id,'dri_id':dri_id, recordTime: time, 'encodedString':result}]
		};
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : sendSuccess,
			onFailure : sendFailure
		});
	})
	.fail(function (errorObject) {
		alert("insert audio fail");
	});
	
}

function playRecordByContent(encodedString) {
//	alert("playRecordByContent"+ encodedString);
	cordova.exec(decodeSuccess, decodeFailure, "EncodeUtilPlugin", "decodeAudio", [encodedString]);
}


/**
 * send audio to server success, so remind the user
 */
function sendSuccess() {
//	alert("send Success");
//	$('.sending').text("OK");
	$('.sending').removeClass('sending');
	setTimeout(function() {alert("receive");receiveEncodeAudio('1', '123', 124, window.tmp);}, 20000);
}

/**
 * send audio to server failure, so remind the user
 */
function sendFailure() {
//	$('.sending').text("fail");
	$('.sending').removeClass('sending');
//	alert("setTimeout");
	setTimeout(function() {alert("receive");receiveEncodeAudio('1', '123', 124, window.tmp);}, 20000);
}

/**
 * encode fail , so remind the user
 * @param result
 */
function encodeFailure(result) {
//	alert("encode fail:" + result);
}

/**
 * receive the encoded string of a audio from push notification, save it to json store
 * PS: we don't save the audio file in android SDcard ,just save the encoded string in json store 
 * decode the encoded string when playing the audio
 * @param result
 */
function receiveEncodeAudio(cus_id, dri_id, recordTime, encodedString) {
	alert(cus_id + " " + dri_id);
//	alert(window.customer.id +  " " + window.backResult.driverInfo.id);
	
	//only handle the current return driver record
	if(dri_id == window.backResult.driverInfo.id && cus_id == window.customer.id) {
		alert("append driver audio");
		var left = $("<div class='left'><img src='../images/defaultPhoto.png' width='40px' height='40px'><span class='triangle-border left'>ccccc</span></div>");
		left.on('tap', function() {playRecordByContent(encodedString);});
		left.appendTo($("#recordHistory"));
		var data = {cus_id: cus_id, dri_id: dri_id, recordTime: recordTime, encodedString : encodedString};
		window.audioJS.add(data, {})
		.then(function () {
			alert("insert audio success");
		})
		.fail(function (errorObject) {
			alert("insert audio fail");
		});
	}
}





